package com.young.dubbo.register;

import com.alibaba.fastjson.JSONObject;
import com.young.dubbo.framework.URL;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ZookeeperRegister {

    private static Logger logger = LoggerFactory.getLogger(ZookeeperRegister.class);

    static CuratorFramework client;

    static {
        RetryPolicy retryPolicy;
        client = CuratorFrameworkFactory.newClient("localhost:2181", new RetryNTimes(3,1000));
        client.start();
    }

    private static Map<String, List<URL>> REGISTER = new HashMap<>();

    public static void register(String interfaceName,URL url){
        try {
            String result = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL)
                    .forPath(String.format("/dubbo/service/%s/%s", interfaceName, JSONObject.toJSONString(url), null));
            logger.info(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static List<URL> get(String interfaceName){
        List<URL> urls = new ArrayList<>();
        try {
            List<String> result = client.getChildren().forPath(String.format("/dubbo/service/%s", interfaceName));
            for (String url : result) {
                urls.add(JSONObject.parseObject(url,URL.class));
            }
            REGISTER.put(interfaceName,urls);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return urls;
    }
}
